package com.gusti.turnos.dao.impl;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Repository;

import com.gusti.turnos.dao.IProjectDao;
import com.gusti.turnos.util.Debug;

/**
 * 
 * @author gusti
 *
 */
@Repository
public abstract class ProjectDao<EntityType> implements IProjectDao<EntityType> {

	@PersistenceContext
	protected EntityManager em;

	@Override
	public EntityType save( EntityType entity ) {
		em.persist( entity );
		return entity;
	}

	@Override
	public EntityType update( EntityType entity ) {
		em.merge( entity );
		return entity;
	}

	@Override
	public void delete( EntityType entity ) {
		em.remove( entity );
	}

	@Override
	public boolean checkUniqueField( String objectClass, String field, String value ) {

		long fieldCount = 0;
		Query query = null;
		try {
			query = em.createQuery( "SELECT COUNT(" + field + ") FROM " + objectClass + " WHERE " + field + " = :value" );
			query.setParameter( "value", value );
			fieldCount = (Long) query.getSingleResult();
		} catch ( Exception e ) {
			Debug.error( e );
		}

		return fieldCount == 0;
	}
}
